<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workflow-templates' }">工作流模板管理</el-breadcrumb-item>
          <el-breadcrumb-item v-if="instance.workflow_id" :to="{ path: `/workflow-templates/${instance.workflow_id}` }">
            模板详情
          </el-breadcrumb-item>
          <el-breadcrumb-item>实例详情</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="action-buttons">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
          <el-button type="primary" @click="handleDuplicate">
            <el-icon><CopyDocument /></el-icon>
            复制实例
          </el-button>
          <el-button type="success" @click="handleSaveAsTemplate">
            <el-icon><Document /></el-icon>
            另存为模板
          </el-button>
          <!-- 新增：未运行状态的运行按钮 -->
          <el-button
            v-if="instance.status === '未运行'"
            type="primary"
            @click="handleStart"
          >
            <el-icon><VideoPlay /></el-icon>
            运行
          </el-button>
          <el-button
            v-if="instance.status === '运行中'"
            type="warning"
            @click="handlePause"
          >
            <el-icon><VideoPause /></el-icon>
            暂停
          </el-button>
          <el-button
            v-if="instance.status === '已暂停'"
            type="success"
            @click="handleResume"
          >
            <el-icon><VideoPlay /></el-icon>
            恢复
          </el-button>
          <el-button
            v-if="instance.status === '失败'"
            type="primary"
            @click="handleRetry"
          >
            <el-icon><Refresh /></el-icon>
            重试
          </el-button>
          <el-button
            v-if="['运行中', '等待中'].includes(instance.status)"
            type="danger"
            @click="handleCancel"
          >
            <el-icon><Close /></el-icon>
            取消
          </el-button>
        </div>
      </div>
    </div>

    <el-card v-loading="loading" class="detail-card">
      <!-- 实例基本信息 -->
      <template #header>
        <div class="card-header">
          <span class="card-title">实例信息</span>
          <el-tag v-if="instance.status" :type="getStatusType(instance.status)" size="large">
            {{ instance.status }}
          </el-tag>
        </div>
      </template>

      <el-descriptions :column="2" border>
        <el-descriptions-item label="实例ID">{{ instance.id }}</el-descriptions-item>
        <el-descriptions-item label="实例名称">{{ instance.instance_name }}</el-descriptions-item>
        <el-descriptions-item label="工作流模板">
          <el-link type="primary" @click="router.push(`/workflow-templates/${instance.template_id}`)">
            {{ instance.template_name }} [v{{ instance.template_version }}]
          </el-link>
        </el-descriptions-item>
        <el-descriptions-item label="触发方式">
          <el-tag v-if="instance.trigger_type === 'manual'" type="primary" size="small">手动触发</el-tag>
          <el-tag v-else type="info" size="small">定时触发</el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="调度类型">
          <el-tag :type="getScheduleTypeTag(instance.schedule_type)" size="small">
            {{ getScheduleTypeLabel(instance.schedule_type) }}
          </el-tag>
          <div v-if="getScheduleConfigDetails(instance)" class="schedule-details">
            {{ getScheduleConfigDetails(instance) }}
          </div>
        </el-descriptions-item>
        <el-descriptions-item label="当前执行节点">
          <el-tag v-if="instance.current_node_id" type="primary">
            {{ instance.current_node_id }}
          </el-tag>
          <span v-else>-</span>
        </el-descriptions-item>
        <el-descriptions-item label="执行耗时">
          {{ instance.duration ? `${instance.duration}秒` : '-' }}
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">
          {{ formatDate(instance.created_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="开始时间">
          {{ formatDate(instance.started_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="结束时间">
          {{ formatDate(instance.finished_at) }}
        </el-descriptions-item>
        <el-descriptions-item label="创建人">
          {{ instance.created_by || '系统' }}
        </el-descriptions-item>
        <el-descriptions-item v-if="instance.error_message" label="错误信息" :span="2">
          <el-alert type="error" :closable="false">
            {{ instance.error_message }}
          </el-alert>
        </el-descriptions-item>
        <!-- <el-descriptions-item v-if="instance.input_params" label="输入参数" :span="2">
          <pre class="params-json">{{ JSON.stringify(instance.input_params, null, 2) }}</pre>
        </el-descriptions-item> -->
      </el-descriptions>
    </el-card>

    <!-- 节点执行记录 -->
    <el-card class="detail-card">
      <template #header>
        <span class="card-title">节点执行记录</span>
      </template>

      <div v-if="instance.nodes_execution && instance.nodes_execution.length > 0">
        <!-- 可视化流程图 -->
        <div class="workflow-visualization">
          <el-steps
            :active="getActiveStep()"
            :process-status="getProcessStatus()"
            align-center
          >
            <el-step
              v-for="(node, index) in instance.nodes_execution"
              :key="node.node_id"
              :title="node.node_name"
              :description="node.node_id"
              :status="getStepStatus(node.status)"
            >
              <template #icon>
                <el-icon v-if="node.status === 'completed'" color="#67C23A"><CircleCheck /></el-icon>
                <el-icon v-else-if="node.status === 'failed'" color="#F56C6C"><CircleClose /></el-icon>
                <el-icon v-else-if="node.status === 'running'" color="#409EFF"><Loading /></el-icon>
                <el-icon v-else color="#909399"><Clock /></el-icon>
              </template>
            </el-step>
          </el-steps>
        </div>

        <!-- 节点详细信息 -->
        <el-collapse accordion class="node-collapse">
          <el-collapse-item
            v-for="(node, index) in instance.nodes_execution"
            :key="node.node_id"
            :name="node.node_id"
          >
            <template #title>
              <div class="node-title">
                <el-tag size="small" type="primary">节点 {{ index + 1 }}</el-tag>
                <span class="node-name">{{ node.node_name }}</span>
                <el-tag size="small">{{ getNodeTypeLabel(node.node_type) }}</el-tag>
                <el-tag :type="getNodeStatusType(node.status)" size="small">
                  {{ node.status }}
                </el-tag>
              </div>
            </template>
            <div class="node-detail">
              <el-descriptions :column="2" border size="small">
                <el-descriptions-item label="节点ID">{{ node.node_id }}</el-descriptions-item>
                <el-descriptions-item label="节点名称">{{ node.node_name }}</el-descriptions-item>
                <el-descriptions-item label="节点类型">{{ getNodeTypeLabel(node.node_type) }}</el-descriptions-item>
                <el-descriptions-item label="状态">
                  <el-tag :type="getNodeStatusType(node.status)">{{ node.status }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="开始时间">
                  {{ formatDate(node.started_at) }}
                </el-descriptions-item>
                <el-descriptions-item label="结束时间">
                  {{ formatDate(node.finished_at) }}
                </el-descriptions-item>
                <el-descriptions-item v-if="node.error_message" label="错误信息" :span="2">
                  <el-alert type="error" :closable="false">{{ node.error_message }}</el-alert>
                </el-descriptions-item>
                <el-descriptions-item v-if="node.output_data" label="输出数据" :span="2">
                  <pre class="output-json">{{ JSON.stringify(node.output_data, null, 2) }}</pre>
                </el-descriptions-item>
              </el-descriptions>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <el-empty v-else description="暂无节点执行记录" />
    </el-card>

    <!-- 执行日志 -->
    <el-card class="detail-card">
      <template #header>
        <div class="card-header">
          <span class="card-title">执行日志</span>
          <div class="log-filters">
            <el-select v-model="logFilters.node_id" placeholder="选择节点" clearable size="small" style="width: 200px">
              <el-option
                v-for="node in instance.nodes_execution"
                :key="node.node_id"
                :label="node.node_name"
                :value="node.node_id"
              />
            </el-select>
            <el-select v-model="logFilters.log_level" placeholder="日志级别" clearable size="small" style="width: 120px">
              <el-option label="INFO" value="INFO" />
              <el-option label="WARN" value="WARN" />
              <el-option label="ERROR" value="ERROR" />
            </el-select>
            <el-button size="small" @click="fetchLogs">
              <el-icon><Refresh /></el-icon>
              刷新
            </el-button>
          </div>
        </div>
      </template>

      <div v-loading="logsLoading" class="logs-container">
        <div v-if="logs.length > 0" class="logs-list">
          <div
            v-for="(log, index) in logs"
            :key="index"
            class="log-item"
            :class="`log-${log.log_level.toLowerCase()}`"
          >
            <span class="log-time">{{ formatDate(log.log_time) }}</span>
            <el-tag :type="getLogLevelType(log.log_level)" size="small">{{ log.log_level }}</el-tag>
            <span v-if="log.node_id" class="log-node">[{{ log.node_id }}]</span>
            <span class="log-message">{{ log.log_message }}</span>
          </div>
        </div>
        <el-empty v-else description="暂无日志" />
      </div>
    </el-card>

    <!-- 重试对话框 -->
    <el-dialog v-model="retryDialogVisible" title="重试工作流" width="500px">
      <el-form label-width="120px">
        <el-form-item label="从哪个节点重试">
          <el-select v-model="retryNodeId" placeholder="选择节点（可选）" clearable>
            <el-option
              v-for="node in instance.nodes_execution"
              :key="node.node_id"
              :label="node.node_name"
              :value="node.node_id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="retryDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmRetry">确定</el-button>
      </template>
    </el-dialog>

    <!-- 复制实例对话框 -->
    <el-dialog v-model="duplicateDialogVisible" title="复制实例" width="700px" :close-on-click-modal="false">
      <el-form :model="duplicateForm" label-width="120px">
        <el-form-item label="新实例名称" required>
          <el-input v-model="duplicateForm.instance_name" placeholder="请输入新实例名称" />
        </el-form-item>

        <el-form-item label="调度类型" required>
          <el-radio-group v-model="duplicateForm.schedule_type" @change="handleDuplicateScheduleTypeChange">
            <el-radio value="manual">立即执行</el-radio>
            <el-radio value="create_only">仅创建</el-radio>
            <el-radio value="scheduled">定时执行（一次性）</el-radio>
            <el-radio value="dependent">依赖执行</el-radio>
          </el-radio-group>
          <div class="form-tip" style="margin-top: 8px;">
            <span v-if="duplicateForm.schedule_type === 'manual'">
              创建后实例将自动进入执行队列（约1分钟内开始执行）
            </span>
            <span v-else-if="duplicateForm.schedule_type === 'create_only'">
              创建后实例状态为"未运行"，需要手动点击"运行"按钮启动
            </span>
            <span v-else-if="duplicateForm.schedule_type === 'scheduled'">
              实例将在指定时间自动执行
            </span>
            <span v-else-if="duplicateForm.schedule_type === 'dependent'">
              当所有依赖实例完成后，此实例将自动执行
            </span>
          </div>
        </el-form-item>

        <!-- 定时执行配置 -->
        <el-form-item v-if="duplicateForm.schedule_type === 'scheduled'" label="执行时间" required>
          <el-date-picker
            v-model="duplicateForm.scheduled_time"
            type="datetime"
            placeholder="选择执行时间"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DDTHH:mm:ss"
            style="width: 100%"
            :disabled-date="disabledDate"
          />
          <div class="form-tip">选择未来的时间点，实例将在该时间自动执行</div>
        </el-form-item>

        <!-- 依赖执行配置 -->
        <el-form-item v-if="duplicateForm.schedule_type === 'dependent'" label="依赖实例" required>
          <el-select
            v-model="duplicateForm.dependency_instance_ids"
            multiple
            filterable
            placeholder="选择依赖的实例（可多选）"
            style="width: 100%"
          >
            <el-option
              v-for="inst in filteredAvailableInstances"
              :key="inst.id"
              :value="inst.id"
            >
              <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
                <span style="flex: 1;">#{{ inst.id }} - {{ inst.instance_name }}</span>
                <el-tag :type="getStatusType(inst.status)" size="small" style="margin-left: 8px;">
                  {{ inst.status }}
                </el-tag>
              </div>
            </el-option>
          </el-select>
          <div class="form-tip">
            只能选择未完成的实例作为依赖（排除已完成、失败、已取消的实例）。当所有依赖实例完成后，此实例将自动执行。
          </div>
        </el-form-item>

        <el-form-item label="创建人">
          <el-input v-model="duplicateForm.created_by" placeholder="请输入创建人信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="duplicateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmDuplicate" :loading="duplicateLoading">下一步</el-button>
      </template>
    </el-dialog>

    <!-- 另存为模板对话框 -->
    <el-dialog v-model="saveAsTemplateDialogVisible" title="另存为模板" width="600px" :close-on-click-modal="false">
      <el-form :model="saveAsTemplateForm" label-width="120px">
        <el-form-item label="模板名称" required>
          <el-input v-model="saveAsTemplateForm.template_name" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="模板描述">
          <el-input
            v-model="saveAsTemplateForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入模板描述"
          />
        </el-form-item>
        <el-form-item label="创建人">
          <el-input v-model="saveAsTemplateForm.created_by" placeholder="请输入创建人" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="saveAsTemplateDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmSaveAsTemplate" :loading="saveAsTemplateLoading">保存</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getWorkflowInstanceDetail,
  getWorkflowInstanceLogs,
  pauseWorkflowInstance,
  resumeWorkflowInstance,
  retryWorkflowInstance,
  cancelWorkflowInstance
} from '@/api/workflow'
import { startInstance } from '@/api/workflowTemplate'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'
import { useWorkflowStore } from '@/stores/workflow'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const templateStore = useWorkflowTemplateStore()
const workflowStore = useWorkflowStore()

const instanceId = ref(parseInt(route.params.id))
const loading = ref(false)
const instance = ref({})

const logs = ref([])
const logsLoading = ref(false)
const logFilters = reactive({
  node_id: undefined,
  log_level: undefined
})

const retryDialogVisible = ref(false)
const retryNodeId = ref(undefined)

// 复制实例相关状态
const duplicateDialogVisible = ref(false)
const duplicateLoading = ref(false)
const duplicateForm = reactive({
  instance_name: '',
  schedule_type: 'manual', // 默认立即执行
  scheduled_time: null,
  dependency_instance_ids: [],
  cron_expression: '',
  created_by: ''
})

// 可用实例列表（用于依赖执行）
const availableInstances = ref([])

// 另存为模板相关状态
const saveAsTemplateDialogVisible = ref(false)
const saveAsTemplateLoading = ref(false)
const saveAsTemplateForm = reactive({
  template_name: '',
  description: '',
  created_by: ''
})

// 节点类型映射
const nodeTypeMap = {
  'create_experiment': '创建实验',
  'download_data': '下载数据',
  'data_processing': '数据处理',
  'condition_branch': '条件分支'
}

const getNodeTypeLabel = (type) => {
  return nodeTypeMap[type] || type
}

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : '-'
}

const getStatusType = (status) => {
  const typeMap = {
    '未运行': 'info',
    '运行中': 'primary',
    '已完成': 'success',
    '失败': 'danger',
    '暂停中': 'warning',
    '已暂停': 'info',
    '等待中': 'warning',
    '已取消': 'info',
    '初始化': 'info'
  }
  return typeMap[status] || 'info'
}

const getScheduleTypeTag = (scheduleType) => {
  const typeMap = {
    'manual': 'info',
    'scheduled': 'primary',
    'dependent': 'warning',
    'cron': 'success'
  }
  return typeMap[scheduleType || 'manual'] || 'info'
}

const getScheduleTypeLabel = (scheduleType) => {
  const labelMap = {
    'manual': '立即执行',
    'scheduled': '定时执行',
    'dependent': '依赖执行',
    'cron': 'CRON定时'
  }
  return labelMap[scheduleType || 'manual'] || scheduleType
}

const getScheduleConfigDetails = (instance) => {
  if (!instance.schedule_config) return ''

  const config = instance.schedule_config
  const scheduleType = instance.schedule_type || 'manual'

  if (scheduleType === 'scheduled' && config.scheduled_time) {
    return `执行时间: ${formatDate(config.scheduled_time)}`
  } else if (scheduleType === 'dependent' && config.dependency_instance_ids) {
    return `依赖实例: ${config.dependency_instance_ids.join(', ')}`
  } else if (scheduleType === 'cron' && config.cron_expression) {
    return `CRON表达式: ${config.cron_expression}`
  }

  return ''
}

// 过滤可用实例 - 只显示未完成的实例
const filteredAvailableInstances = computed(() => {
  const completedStatuses = ['已完成', '失败', '已取消']
  return availableInstances.value.filter(inst =>
    !completedStatuses.includes(inst.status)
  )
})

// 禁用过去的日期
const disabledDate = (time) => {
  return time.getTime() < Date.now()
}

// 切换调度类型时重置相关配置
const handleDuplicateScheduleTypeChange = () => {
  duplicateForm.scheduled_time = null
  duplicateForm.dependency_instance_ids = []
  duplicateForm.cron_expression = ''
}

const getNodeStatusType = (status) => {
  const typeMap = {
    'completed': 'success',
    'failed': 'danger',
    'running': 'primary',
    'pending': 'info',
    'waiting': 'warning'
  }
  return typeMap[status] || 'info'
}

const getLogLevelType = (level) => {
  const typeMap = {
    'INFO': 'info',
    'WARN': 'warning',
    'ERROR': 'danger'
  }
  return typeMap[level] || 'info'
}

const getActiveStep = () => {
  if (!instance.value.nodes_execution) return 0
  const runningIndex = instance.value.nodes_execution.findIndex(n => n.status === 'running')
  if (runningIndex >= 0) return runningIndex
  const completedCount = instance.value.nodes_execution.filter(n => n.status === 'completed').length
  return completedCount
}

const getProcessStatus = () => {
  if (instance.value.status === '失败') return 'error'
  if (instance.value.status === '已完成') return 'success'
  if (instance.value.status === '运行中') return 'process'
  return 'wait'
}

const getStepStatus = (nodeStatus) => {
  const statusMap = {
    'completed': 'success',
    'failed': 'error',
    'running': 'process',
    'pending': 'wait',
    'waiting': 'wait'
  }
  return statusMap[nodeStatus] || 'wait'
}

const fetchInstance = async () => {
  loading.value = true
  try {
    const data = await getWorkflowInstanceDetail(instanceId.value)
    instance.value = data
  } catch (error) {
    console.error('获取实例详情失败:', error)
    ElMessage.error('获取实例详情失败')
  } finally {
    loading.value = false
  }
}

const fetchLogs = async () => {
  logsLoading.value = true
  try {
    const data = await getWorkflowInstanceLogs(instanceId.value, {
      node_id: logFilters.node_id,
      log_level: logFilters.log_level
    })
    logs.value = data.logs || []
  } catch (error) {
    console.error('获取日志失败:', error)
    ElMessage.error('获取日志失败')
  } finally {
    logsLoading.value = false
  }
}

const handleBack = () => {
  router.push('/monitoring')
  // if (instance.value.workflow_id) {
  //   router.push(`/workflow-templates/${instance.value.workflow_id}`)
  // } else {
  //   router.push('/workflow-templates')
  // }
}

// 新增：启动未运行的实例
const handleStart = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要启动这个工作流实例吗？启动后将进入调度队列执行。',
      '确认启动',
      {
        confirmButtonText: '启动',
        cancelButtonText: '取消',
        type: 'info'
      }
    )

    await startInstance(instanceId.value)
    ElMessage.success('实例已启动，等待调度执行（约1分钟内）')

    setTimeout(() => {
      fetchInstance()
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('启动失败:', error)
      ElMessage.error(error.response?.data?.detail || '启动实例失败')
    }
  }
}

const handlePause = async () => {
  try {
    await ElMessageBox.confirm('确定要暂停这个工作流实例吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await pauseWorkflowInstance(instanceId.value)
    ElMessage.success('暂停请求已发送')

    setTimeout(() => {
      fetchInstance()
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('暂停失败:', error)
    }
  }
}

const handleResume = async () => {
  try {
    await ElMessageBox.confirm('确定要恢复这个工作流实例吗？', '确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    })

    await resumeWorkflowInstance(instanceId.value)
    ElMessage.success('工作流已恢复执行')

    setTimeout(() => {
      fetchInstance()
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('恢复失败:', error)
    }
  }
}

const handleRetry = () => {
  retryNodeId.value = undefined
  retryDialogVisible.value = true
}

const confirmRetry = async () => {
  try {
    await retryWorkflowInstance(instanceId.value, {
      from_node_id: retryNodeId.value || undefined
    })
    ElMessage.success('工作流已开始重试')
    retryDialogVisible.value = false

    setTimeout(() => {
      fetchInstance()
    }, 1000)
  } catch (error) {
    console.error('重试失败:', error)
  }
}

const handleCancel = async () => {
  try {
    await ElMessageBox.confirm('确定要取消这个工作流实例吗？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await cancelWorkflowInstance(instanceId.value)
    ElMessage.success('工作流已取消')

    setTimeout(() => {
      fetchInstance()
    }, 1000)
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消失败:', error)
    }
  }
}

const handleDuplicate = async () => {
  try {
    // 加载可用实例列表（用于依赖执行）
    const instancesData = await workflowStore.fetchWorkflowInstances({
      page: 1,
      page_size: 100,
      include_not_started: true
    })
    availableInstances.value = instancesData.items || []

    // 预填充表单
    duplicateForm.instance_name = `${instance.value.instance_name}_副本_${dayjs().format('YYYYMMDDHHmmss')}`
    duplicateForm.schedule_type = 'manual' // 默认立即执行
    duplicateForm.scheduled_time = null
    duplicateForm.dependency_instance_ids = []
    duplicateForm.cron_expression = ''
    duplicateForm.created_by = ''

    duplicateDialogVisible.value = true
  } catch (error) {
    console.error('加载数据失败:', error)
    ElMessage.error('加载数据失败')
  }
}

const confirmDuplicate = () => {
  if (!duplicateForm.instance_name) {
    ElMessage.warning('请输入实例名称')
    return
  }

  // 验证调度配置
  if (duplicateForm.schedule_type === 'scheduled' && !duplicateForm.scheduled_time) {
    ElMessage.warning('请选择执行时间')
    return
  }

  if (duplicateForm.schedule_type === 'dependent' && (!duplicateForm.dependency_instance_ids || duplicateForm.dependency_instance_ids.length === 0)) {
    ElMessage.warning('请选择至少一个依赖实例')
    return
  }

  // 构建调度配置
  let scheduleConfig = null
  if (duplicateForm.schedule_type === 'scheduled') {
    scheduleConfig = {
      scheduled_time: duplicateForm.scheduled_time
    }
  } else if (duplicateForm.schedule_type === 'dependent') {
    scheduleConfig = {
      dependency_instance_ids: duplicateForm.dependency_instance_ids
    }
  }

  // 关闭对话框
  duplicateDialogVisible.value = false

  // 跳转到编辑页面，通过 query 传递参数
  // 传递源实例ID，编辑页面将从后端获取 workflow_definition_snapshot
  router.push({
    path: '/workflow-instances/create',
    query: {
      template_id: instance.value.template_id,
      template_name: instance.value.template_name || '',
      instance_name: duplicateForm.instance_name,
      input_params: JSON.stringify(instance.value.input_params || {}), // 使用当前实例的参数
      trigger_type: duplicateForm.schedule_type === 'cron' ? 'cron' : 'manual',
      schedule_type: duplicateForm.schedule_type,
      schedule_config: scheduleConfig ? JSON.stringify(scheduleConfig) : '',
      cron_enabled: false,
      cron_expression: '',
      created_by: duplicateForm.created_by || '',
      // 关键：传递源实例ID，用于从后端获取 workflow_definition_snapshot
      source_instance_id: instanceId.value,
      is_duplicate: 'true' // 标记这是复制操作
    }
  })
}

const handleSaveAsTemplate = () => {
  // 预填充表单
  saveAsTemplateForm.template_name = `${instance.value.instance_name}_模板`
  saveAsTemplateForm.description = `基于实例 ${instance.value.instance_name} 创建的模板`
  saveAsTemplateForm.created_by = instance.value.created_by || ''

  saveAsTemplateDialogVisible.value = true
}

const confirmSaveAsTemplate = async () => {
  if (!saveAsTemplateForm.template_name) {
    ElMessage.warning('请输入模板名称')
    return
  }

  saveAsTemplateLoading.value = true
  try {
    const result = await templateStore.saveInstanceAsTemplate(instanceId.value, {
      template_name: saveAsTemplateForm.template_name,
      description: saveAsTemplateForm.description,
      created_by: saveAsTemplateForm.created_by || '系统'
    })

    ElMessage.success('模板保存成功')
    saveAsTemplateDialogVisible.value = false

    // 询问是否跳转到模板页面
    ElMessageBox.confirm('是否跳转到新创建的模板？', '提示', {
      confirmButtonText: '跳转',
      cancelButtonText: '留在当前页',
      type: 'info'
    }).then(() => {
      router.push(`/workflow-templates/${result.id}`)
    }).catch(() => {
      // 用户选择留在当前页
    })
  } catch (error) {
    console.error('另存为模板失败:', error)
    ElMessage.error(error.response?.data?.detail || '另存为模板失败')
  } finally {
    saveAsTemplateLoading.value = false
  }
}

// 监听日志筛选条件变化
watch(() => [logFilters.node_id, logFilters.log_level], () => {
  fetchLogs()
}, { deep: true })

onMounted(() => {
  fetchInstance()
  fetchLogs()

  // 如果实例正在运行，定时刷新
  const refreshInterval = setInterval(() => {
    if (['运行中', '等待中'].includes(instance.value.status)) {
      fetchInstance()
      fetchLogs()
    } else {
      clearInterval(refreshInterval)
    }
  }, 300000) // 每300(秒) * 1000刷新一次
})
</script>

<style lang="scss" scoped>
.detail-card {
  margin-bottom: 20px;

  :deep(.el-card__header) {
    padding: 16px 20px;
  }
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
}

.params-json,
.output-json {
  background-color: #f5f7fa;
  padding: 10px;
  border-radius: 4px;
  font-size: 12px;
  line-height: 1.6;
  max-height: 200px;
  overflow: auto;
}

.workflow-visualization {
  margin-bottom: 30px;
  padding: 20px 0;
}

.node-collapse {
  margin-top: 20px;
}

.node-title {
  display: flex;
  align-items: center;
  gap: 10px;
  width: 100%;

  .node-name {
    font-weight: 500;
    flex: 1;
  }
}

.node-detail {
  padding: 10px 0;
}

.log-filters {
  display: flex;
  gap: 10px;
  align-items: center;
}

.logs-container {
  min-height: 200px;
  max-height: 600px;
  overflow-y: auto;
}

.logs-list {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.log-item {
  display: flex;
  align-items: center;
  gap: 10px;
  padding: 8px 12px;
  background-color: #f5f7fa;
  border-radius: 4px;
  font-size: 13px;

  &.log-error {
    background-color: #fef0f0;
  }

  &.log-warn {
    background-color: #fdf6ec;
  }

  .log-time {
    color: #909399;
    font-size: 12px;
    min-width: 150px;
  }

  .log-node {
    color: #409eff;
    font-weight: 500;
  }

  .log-message {
    flex: 1;
    word-break: break-all;
  }
}

.page-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.schedule-details {
  margin-top: 5px;
  font-size: 13px;
  color: #606266;
}
</style>
